import {reqCartList,reqDeletCartById,reqUpdateCheckedById} from "@/api"
const state = {
    cartList:[]
};
const mutations = {
    GETCARTLIST(state,cartList) {
        state.cartList = cartList
    }
};
const actions = {
    // 获取购物车列表的数据
    async getCartList({commit}) {
        let result = await reqCartList();
        if(result.code == 200) {
            commit('GETCARTLIST',result.data)
        }
    },
    // 删除购物车数据
    async deleteCartListById({commit},skuId) {
        let result = await reqDeletCartById(skuId);
        if(result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 改变商品的状态
    async updateCheckedById({commit},{skuId,isChecked}) {
        let result = await reqUpdateCheckedById(skuId,isChecked);
        if(result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 删除全部勾选的产品
    deleteAllCheckedCart({dispatch,getters}) {
        // context：小仓库，上下文
        let promiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            if(item.isChecked == 1) {
                promiseAll.push(dispatch('deleteCartListById',item.skuId))
            }
            return Promise.all(promiseAll)
        });
    },
    // 全选改变商品状态
    updateAllCartIsChecked({dispatch,getters},isChecked) {
        let promiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            promiseAll.push(dispatch("updateCheckedById",{skuId:item.skuId,isChecked}))
        })
        return Promise.all(promiseAll)
    }
};
const getters = {
    cartList() {
        return state.cartList[0] || {}
    }
};
export default {
    state,
    mutations,
    actions,
    getters
}